const Router = require('koa-router')
const axios = require('axios')
const MemoryFS = require('memory-fs')// 不把文件写入磁盘，只写入硬盘
const webpack = require('webpack')
const VueServerRender = require('vue-server-renderer')
const fs = require('fs')
const path = require('path')
const serverConfig = require('../../config/webpack.config.server.js')
const serverCompiler = webpack(serverConfig)
const serverRender = require('./server-render')
const mfs = new MemoryFS()
// 指定webpack输出目录在mfs里面
serverCompiler.outputFileSystem = mfs
let bundle
serverCompiler.watch({}, (err, stats) => {
  if (err) throw err
  stats = stats.toJson()
  stats.errors.forEach(err => console.log(err))
  stats.warnings.forEach(warn => console.log(warn))
  const bundlePath = path.join(
    serverConfig.output.path,
    'vue-ssr-server-bundle.json'
  )
  bundle = JSON.parse(mfs.readFileSync(bundlePath, 'utf-8'))
  console.log('new bundle generated')
})
const handleSSR = async (ctx) => {
  if (!bundle) {
    ctx.body = 'Waiting ...'
    return
  }
  const clientManifestResp = await axios.get('http://127.0.0.1:8080/vue-ssr-client-manifest.json')
  const clientManifest = clientManifestResp.data
  console.log(clientManifest)
  const template = fs.readFileSync(path.join(__dirname, '../server.template.ejs'), 'utf-8')
  const render = VueServerRender.createBundleRenderer(bundle, {
    inject: false,
    clientManifest
  })
  await serverRender(ctx, render, template)
}
const router = new Router()
router.get('*', handleSSR)
module.exports = router
